import Mock from 'mockjs';
import {getResponse} from './common';

let userList = [];

const count = 300;

for(let i = 0; i < count; i++){
  userList.push(Mock.mock({
    id: '@increment(1)',
    timestamp: +Mock.Random.date('T'),
    username: '@first',
    nickname: '@cname',
    job: '@cword(2, 3)',
    school: '@cword(2,4)学校',
    mobile: '13@integer(100000000, 999999999)',
    email: '@email',
    introduct: '@cparagraph(1, 2)',
    isMock: true
  }));
};
// userList = userList.slice(295, 300);
export default {
  getList: (option) => {
    let {page, size, search} = JSON.parse(option.body);
    let startIndex = (page - 1) * size;
    let resultList = [];
    if (search) {
      // 如果有查找条件
      resultList = userList.filter((item) => {
        let isResult = true;
        let keys = Object.keys(search);
        for(let i = 0; i < keys.length; i++) {
          // 如果查看条件内容为空，则全部符合
          if(!search[keys[i]]) continue;
          // 如果查找条件不存在对象属性中，不做处理
          // console.log(keys[i], item[keys[i]], search[keys[i]], Object.keys(item));
          // if(Object.keys(item).indexOf(keys[i]) === -1) continue;
          // 如果对象属性中存在查找条件的内容
          if(item[keys[i]] && item[keys[i]].toUpperCase().indexOf(search[keys[i]].toUpperCase()) > -1) continue;
          isResult = false;
          break;
        }
        return isResult;
      })
    } else {
      resultList = userList.slice();
    }
    let list = resultList.sort((a, b) => b.id - a.id).slice(startIndex, startIndex + size);
    let res = getResponse();
    res.data = {list, total: resultList.length};
    return res;
  },
  del: (option) => {
    let keys = JSON.parse(option.body);
    for(let i = 0; i < keys.length; i++) {
      for(let j = 0; j < userList.length; j++) {
        if(userList[j].id === keys[i]) {
          userList.splice(j, 1);
          break;
        }
      }
    }
    return getResponse();
  },
  edit: (option) => {
    let user = JSON.parse(option.body);
    if(user.id) {
      let index = userList.findIndex(item => item.id === user.id);
      userList.splice(index, 1, user);
    } else {
      user.id = userList[userList.length - 1].id + 1;
      userList.push(user);
    }
    // console.log(userList);
    return getResponse();
  }
}